
import md5 from "md5"
import axios, {AxiosResponse} from "axios";

interface TResponse {
  error_code: number
  trans_result: {
    dst: string;
    src: string
  }[]
}
class Translate {
  public appId = ''
  public secretKey = ''
  constructor() {
    const { VITE_APPID, VITE_SECRET_KEY } = import.meta.env
    this.appId = VITE_APPID
    this.secretKey = VITE_SECRET_KEY
  }

  public translate = (word: string, from: string,  to: string) => {
    return new Promise((resolve, reject) => {
      const salt = this.randomNum()
      const sign = md5(`${this.appId}${word}${salt}${this.secretKey}`)
      axios({
        url:  '/tr',
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data:  {
          q: word,
          appid: this.appId,
          salt,
          from: from,
          to: to,
          sign: sign
        }
      }).then((res: AxiosResponse<TResponse>) => {
        const {  status, data, statusText } = res
        if (data.error_code && data.error_code !== 500) {
          reject(this.checkErrorCode(data.error_code))
        } else {
          if (status === 200) {
            resolve(data.trans_result)
          } else {
            reject(statusText)
          }
        }
      }).catch(error => {
        reject(error)
      })
    })
  }

  private checkErrorCode = (code: number) => {
    switch (code) {
      case 52001:
        return '请求超时, 请重试'
      case 52002:
        return '系统错误, 请重试'
      case 52003:
        return '未授权用户'
      case 54000:
        return '必填参数为空'
      case 54001:
        return '签名错误'
      case 54003:
        return '访问频率受限, 请降低您的调用频率，或进行身份认证后切换为高级版/尊享版'
      case 54004:
        return '账户余额不足'
      case 54005:
        return '长query请求频繁, 请降低长query的发送频率，3s后再试'
      case 58000:
        return '客户端IP非法'
      case 58001:
        return '译文语言方向不支持'
      case 58002:
        return '服务当前已关闭'
      case 90107:
        return '认证未通过或未生效'
      default: return '系统错误, 请重试'
    }
  }

  private randomNum = () => {
    return new Array(10).fill(null).reduce((cur) => {
      cur += Math.floor(Math.random() * 10)
      return cur
    }, '')
  }
}

export const { translate } = new Translate()
